package com.y.fund.web;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import com.y.fund.aacore.data.DataVo;
import com.y.fund.aacore.enums.BoolVal;
import com.y.fund.asyncs.LogoutRcdExcludeNewRecordAsync;
import com.y.fund.consts.ConstAttr;
import com.y.fund.domain.mem.MB13UserInfo;
import com.y.fund.domain.mem.MB15LoginRecord;
import com.y.fund.handler.CurrLgnUserVo;
import com.y.fund.service.CommService;
import com.y.fund.utils.DateTimeUtil;
import com.y.fund.utils.IdGenerator;
import com.y.fund.utils.JwtUtil;
import com.y.fund.utils.RedisUtil;
import com.y.fund.web.aavo.com.LgnUserVo;

public abstract class BaseController {
	
	@Autowired
	protected CommService commService;

	@Autowired
	protected LogoutRcdExcludeNewRecordAsync logoutRcdExcludeNewRecordAsync;
	
	@Autowired
	private RedisUtil redisUtil;

	/** Parse the error message of validation annotation validation  */
	 public DataVo parseBindingResult(BindingResult bindingResult) throws Exception{
		 if(null == bindingResult) {
			 return null;
		 }
		 if (bindingResult.hasErrors()) {
			StringBuffer sb = new StringBuffer(); 
            for (ObjectError objectError : bindingResult.getAllErrors()) {
                FieldError fieldError = (FieldError) objectError;
                sb.append("[").append(fieldError.getField()).append("]：").append(objectError.getDefaultMessage()).append("；");
            }
            return DataVo.Fail(sb.toString());
        }
		return null;
	}

	/** 用户登录成功，记录用户登录信息   */
	public Map<String, Object> recordLgnTrace(String lgnName, MB13UserInfo user, String clientType, Long invalidMinutes) throws IOException {
		final String ctime = DateTimeUtil.NowTime();
		final String lgnId = IdGenerator.Id32();
		final String userId = user.getId();
		
		LgnUserVo luv = new LgnUserVo(BoolVal.No.getVal(), lgnId, userId, user.getCode(), user.getName());
		luv.setClientType(clientType);
		
		MB15LoginRecord ult = MB15LoginRecord.Login(lgnId, user.getId(), user.getCode(), user.getName(), ctime, clientType);
		
		
		commService.addObj(ult);
		
		Map<String, Object> lgnInfo = new LinkedHashMap<String, Object>();
		lgnInfo.put("lgnId", lgnId);
		lgnInfo.put("userName", user.getName());
		lgnInfo.put("lgnTime", ctime);
		lgnInfo.put("userCode", user.getCode());

		String token = JwtUtil.CreateUsrIdJWT(lgnId, clientType, user.getId(), ConstAttr.LGN_EXPIRES_MILLIS);
		lgnInfo.put(ConstAttr.AUTH_TOKEN_KEY, token);

		cacheCurrLgnInfo(invalidMinutes, luv);

		logoutRcdExcludeNewRecordAsync.exec(userId, clientType, ctime, lgnId);
		
		return lgnInfo;
	}

	protected void cacheCurrLgnInfo(Long invalidMinutes, LgnUserVo luv) {
		redisUtil.set(LgnUserVo.GetCacheKey(luv.getClientType(), luv.getUserId()), luv, invalidMinutes);
		CurrLgnUserVo.Set(luv);
	}
	
}
